package com.xiangxiao.rpan.authority.service.impl;

import com.xiangxiao.rpan.authority.constant.GlobalConsts;
import com.xiangxiao.rpan.authority.constant.ResponseCode;
import com.xiangxiao.rpan.authority.exception.MsgException;
import com.xiangxiao.rpan.authority.model.UserInfo;
import com.xiangxiao.rpan.authority.model.UserRoleInfo;
import com.xiangxiao.rpan.authority.oauth.UserOAuthDetail;
import com.xiangxiao.rpan.authority.service.IRoleService;
import com.xiangxiao.rpan.authority.service.UserService;
import com.xiangxiao.rpan.authority.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/3/15 17:47
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
  @Autowired
  private UserService userService;
  @Autowired
  private IRoleService roleService;

  @Override
  public UserDetails loadUserByUsername(String account) {
    UserVo user = userService.findUserByAccount(account);
    if (user == null || user.getDeletedFlg() == GlobalConsts.STATUS_DELETED) {
      log.info("账号不存在account={}", account);
      throw new MsgException("账号不存在，请联系管理员！", ResponseCode.ACCOUNT_NOT_EXIST);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.set(2048, Calendar.DECEMBER, 29);
    Date endTime = user.getEndTime() == null ? calendar.getTime() : user.getEndTime();
    boolean expired = (user.getExpired() != null && user.getExpired() == GlobalConsts.STATUS_EXPIRED) || (endTime != null && new Date().compareTo(endTime) >= 0);
    if (expired) {
      throw new MsgException("您的账号已过期，请联系管理员！", ResponseCode.ACCOUNT_DISABLED);
    }
    if (user.getStatus() == GlobalConsts.STATUS_UN_USE) {
      throw new MsgException("您的账号已锁定，请联系管理员！", ResponseCode.ACCOUNT_LOCKED);
    }

    List<UserRoleInfo> userRoleInfo = roleService.findRoleInfoOfUser(user.getId(), 0);
    UserInfo userInfo = new UserInfo();
    userInfo.setUserVo(user);
    userInfo.setUserRoleInfos(userRoleInfo);
    return new UserOAuthDetail(account, userInfo);
  }
}
